package cn.com.generaldata.os.ws.impl;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Streams;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.view.JspView;
import org.nutz.mvc.view.ServerRedirectView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.constant.ReportConstant;
import cn.com.generaldata.os.newpojo.SystemCodedic;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.AuthorFunc;
import cn.com.generaldata.os.pojo.Authority;
import cn.com.generaldata.os.pojo.Industry;
import cn.com.generaldata.os.pojo.Role;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.pojo.UserIndustry;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.service.common.AuthorityService;
import cn.com.generaldata.os.service.common.IndustryService;
import cn.com.generaldata.os.service.common.RoleService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.service.impl.UnitService;
import cn.com.generaldata.os.service.intf.IndicatorServiceInterface;
import cn.com.generaldata.os.util.CommonUtil;
import cn.com.generaldata.os.util.MD5Util;
import cn.com.generaldata.os.vo.AuthorityVO;
import cn.com.generaldata.os.vo.FuncVO;
import cn.com.generaldata.os.vo.IndustryVO;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.UnitVO;
import cn.com.generaldata.os.vo.UserVO;

import com.google.common.net.HttpHeaders;

@InjectName
@Component
@IocBean
public class UserWS {
	private static Logger log = LoggerFactory.getLogger(UserWS.class);

	private static final String DEFAULT_PASSWORD = "12345678";

	@Autowired
	private UserService userService;

	@Autowired
	private IndicatorServiceInterface indicatorService;

	@Autowired
	private UnitService unitService;

	@Autowired
	private IndustryService industryService;

	@Autowired
	private AreaService areaService;

	@Autowired
	private AuthorityService authorService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private UnitWS unitWS;

	@Autowired
	private IndustryWS industryWS;

	private List<Integer> yearList;

	private List<cn.com.generaldata.os.vo.RoleVO> roleList;

	@PostConstruct
	public void init() {

		// 获取当前日期
		Calendar cal = Calendar.getInstance();
		int tyear = cal.get(Calendar.YEAR);

		yearList = new ArrayList<Integer>();
		for (int i = tyear; i >= 1997; i--) {
			yearList.add(i);
		}

		roleList = unitWS.queryRoles();

	}

	@At("/role/edit")
	@Ok("jsp:/static/admin/role/edit")
	public void getFuncs(@Param("id") String id, HttpServletRequest request) {

		AuthorityVO authorityVo = queryAuthorById(id);
		List<FuncVO> allFuncs = getAllFuncs();
		List<FuncVO> selectFuncs = getFuncsByAuthor(id);

		for (FuncVO funcVoAll : allFuncs) {
			for (FuncVO funcVoselect : selectFuncs) {
				if (funcVoAll.getId() == funcVoselect.getId()) {
					funcVoAll.setCheck(true);
					break;
				}
			}
		}
		request.setAttribute("authorityVo", authorityVo);
		request.setAttribute("allFuncs", allFuncs);
		request.setAttribute("selectFuncs", selectFuncs);

	}

	@At("/role/downloadUnitTemple")
	@Ok("void")
	public void unitTemple(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String encodedfileName = new String("单位导入模板.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		try {
			indicatorService.downUnitTemple(out);
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	@At("/role/unitList")
	@Ok("jsp:/static/admin/unit/list")
	public ResultVO<cn.com.generaldata.os.vo.UnitVO> queryAreaUnits(@Param("unitName") String unitName,
			@Param("roleId") String roleId, @Param("createYear") String createYear, @Param("areaId") String areaId,
			@Param("p") Integer pageNum, @Param("unitNo") String unitNo, HttpServletRequest request) {

		//获得录入年份列表
		request.setAttribute("yearList", yearList);

		request.setAttribute("roleList", roleList);

		List<SystemCodedic> sysList = unitWS.queryType();
		request.setAttribute("sysList", sysList);

		String hql = "from Unit as u where status='1'";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(areaId)) {
			List<Area> list = new ArrayList<Area>();
			List<Area> areaList = areaService.findChildren(areaId, list);
			List<String> areaIds = new ArrayList<String>();
			areaIds.add(areaId);
			for (Area area : areaList) {
				areaIds.add(area.getId());
			}
			hql += " and u.area.id in (:areaIds)";
			map.put("areaIds", areaIds.toArray());
		}

		if (StringUtils.isNotBlank(unitName)) {
			hql += " and u.unitName like:unitName";
			map.put("unitName", "%" + unitName.trim() + "%");
		}
		if (StringUtils.isNotBlank(unitNo)) {
			hql += " and u.superCompanyCode= :unitNo";
			map.put("unitNo", unitNo);
		}
		if (StringUtils.isNotBlank(roleId)) {
			hql += " and u.role.id=:roleId";
			String unitPro = "";
			// 涉海企业用户
			if (ReportConstant.SHEHAI_UNIT.equals(roleId)) {
				roleId = "3";
				unitPro = "1";
				hql += " and u.unitProper like :unitPro";
				map.put("unitPro", "%" + unitPro + "%");
			}
			// 用海企业用户
			else if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				unitPro = "2";
				hql += " and u.unitProper like :unitPro";
				map.put("unitPro", "%" + unitPro + "%");
			}
			map.put("roleId", roleId.trim());
		}
		if (StringUtils.isNotBlank(createYear)) {
			hql += " and u.createYear=:createYear";
			map.put("createYear", createYear.trim());
		}
		hql += " order by u.createYear desc";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return unitWS.toVoResult(unitService.queryUnitsByhql(hql, map, page));
	}

	@At("/role/add")
	@Ok("jsp:/static/admin/role/add")
	public void addFuncs(HttpServletRequest request) {

		List<FuncVO> allFuncs = getAllFuncs();
		request.setAttribute("allFuncs", allFuncs);

	}

	public AuthorityVO queryAuthorById(String id) {
		Authority author = authorService.getAuthority(id);
		AuthorityVO vAuthor = new AuthorityVO();
		try {
			BeanUtils.copyProperties(vAuthor, author);
			String funcs = "";
			Set<AuthorFunc> authorFunc = author.getAuthorFunc();
			for (AuthorFunc func : authorFunc) {
				funcs += func.getFunc() + "  ";
			}
			vAuthor.setFuncs(funcs);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("转换权限角色出错", e);
		}
		return vAuthor;
	}

	public List<FuncVO> getAllFuncs() {
		return authorService.getAllFuncs();
	}

	public void addAuthor(AuthorityVO vAuthor) {
		if (vAuthor.getId() != null && !"".equals(vAuthor.getId())) {
			authorService.modifyAuthor(vAuthor);
		} else {
			authorService.addAuthor(vAuthor);
		}
	}

	@At("/role/modify")
	@Ok("jsp:/static/admin/role/ok")
	public void modifyAuthor(@Param("authorName") String name, @Param("id") String id, @Param("func") String func,
			HttpServletRequest request) {
		AuthorityVO vAuthor = new AuthorityVO();
		vAuthor.setId(id);
		vAuthor.setAuthorName(name);
		vAuthor.setFuncs(func);
		authorService.modifyAuthor(vAuthor);
		request.setAttribute("msg", "修改成功。");
	}

	@At("/role/insert")
	@Ok("jsp:/static/admin/role/ok")
	public void insertAuthor(@Param("authorName") String name, @Param("func") String func, HttpServletRequest request) {
		AuthorityVO vAuthor = new AuthorityVO();
		vAuthor.setAuthorName(name);
		vAuthor.setFuncs(func);
		authorService.addAuthor(vAuthor);
		request.setAttribute("msg", "增加成功。");
	}

	public List<FuncVO> getFuncsByAuthor(String aid) {
		return authorService.getFuncsByAuthor(aid);
	}

	public boolean findUserByAuthor(String aid) {
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "authorId", aid));
		cn.com.generaldata.os.paging.Result result = userService.queryUsers(filter, null);
		List<cn.com.generaldata.os.pojo.User> list = (List<cn.com.generaldata.os.pojo.User>) result
				.getOperationResult();
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

	public void deleteAuthor(String id) {
		authorService.deleteAuthor(id);
	}

	@At("/role/list")
	@Ok("jsp:/static/admin/role/list")
	public ResultVO<AuthorityVO> queryAuthority(@Param("authorName") String name, @Param("p") Integer pageNum) {
		Filter filter = new Filter();
		if (name != null && !"".equals(name)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "authorName", "%" + name.trim() + "%"));
		}
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		cn.com.generaldata.os.paging.Result result = authorService.queryAuthority(filter, page);
		ResultVO<AuthorityVO> vResult = new ResultVO<AuthorityVO>();
		if (result != null) {
			List<AuthorityVO> operationResult = (List<AuthorityVO>) result.getOperationResult();
			for (AuthorityVO vo : operationResult) {
				boolean enable = findUserByAuthor(vo.getId());
				vo.setEnable(enable);
			}
			vResult.setOperationResult(operationResult);
			vResult.setPageNumber(result.getPageNumber());
			vResult.setPageSize(result.getPageSize());
			vResult.setTotalCount(result.getTotalCount());
		}
		return vResult;
	}

	public String createUser(UserVO user) {
		if (user != null) {
			user.setUserPasswd(DEFAULT_PASSWORD);
		}
		String createUser = userService.createUser(toPojo(user));
		user.setId(createUser);
		modifyUserIndustryIds(user);
		addEnterpriseIndustryIds(user);
		return createUser;
	}

	@At("/user/modify")
	@Ok("jsp:/static/admin/role/ok")
	public void modifyUserInfo(@Param("dustryId") String dustryId, @Param("userLoginname") String userLoginname,
			@Param("authorId") String authorId, @Param("unitId") String unitId,
			@Param("enterpriseUserUseSystem") Integer enterpriseUserUseSystem, @Param("userId") String userId,
			HttpServletRequest request) {

		UserVO userVO = queryUserById(userId);
		User user = toPojo(userVO);

		user.setUserLoginname(userLoginname);
		user.setAuthorId(authorId);
		Unit unit = unitService.queryUnitById(unitId);
		user.setUserUnit(unit);
		user.setEnterpriseUserUseSystem(enterpriseUserUseSystem);
		userService.modifyUser(user);

		List<Industry> industryList = new ArrayList<Industry>();
		if (dustryId != null) {
			String[] arr = dustryId.split(",");
			List<String> dustryIdList = Arrays.asList(arr);
			for (String id : dustryIdList) {
				industryList.add(industryService.queryIndustryById(id));
			}
		}
		userService.modifyIndustry(user, industryList);

		request.setAttribute("msg", "修改成功。");

	}

	public UserVO modifyUser(UserVO user) {
		cn.com.generaldata.os.pojo.User existUser = userService.checkLoginname(user.getUserLoginname());
		if (existUser != null && !user.getId().equals(existUser.getId())) {
			// throw new
			// CommonException(ExceptionConstant.MSG_DUPLICATE_UNIT_NAME);
			// log.error("existUser不为空");
			return null;
		}
		// 如果是涉海企业或部门用户
		if (user.getRoleId().equals("3") || user.getRoleId().equals("5")) {
			// 查看企业是否存在用户
			existUser = userService.checkUnitname(user.getUserUnitId().trim(), null);
			if (existUser != null && !user.getId().equals(existUser.getId())) {
				// throw new
				// CommonException(ExceptionConstant.MSG_DUPLICATE_UNIT_NAME);
				return null;
			}
		}
		if (user.getUserIndustrys() != null) {
			modifyUserIndustryIds(user);
		}
		if (user.getEnterpriseIndustrys() != null) {
			addEnterpriseIndustryIds(user);
		}
		return userService.toVo(userService.modifyUser(toPojo(user)));
	}

	@At("/dataManage/viewExportUser")
	@Ok("jsp:/static/ocean/dataManage/viewUser")
	public UserVO viewUser(@Param("id") String id) {
		return this.queryUserById(id);
	}

	public UserVO queryUserById(String id) {
		return userService.toVo(userService.queryUserById(id));
	}

	public UserVO login(String loginName, String password) {
		return userService.toVo(userService.login(loginName, password));
	}

	public ResultVO<UserVO> queryUsersByArea(String loginName, String roleId, String unitName, String areaId,
			Integer pageNum, String unitNo) {
		String hql = "from User us where role.id<>'1'";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}

		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}

		if (StringUtils.isNotBlank(roleId)) {
			String unitPro = "";
			// 涉海企业用户
			if (ReportConstant.SHEHAI_UNIT.equals(roleId)) {
				roleId = "3";
				unitPro = "1";
				hql += " and exists(select un.id from Unit un where us.userUnit.id=un.id and un.unitProper like :unitProper)";
				map.put("unitProper", "%" + unitPro + "%");
			}
			// 用海企业用户
			else if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				unitPro = "2";
				hql += " and exists(select un.id from Unit un where us.userUnit.id=un.id and un.unitProper like :unitProper)";
				map.put("unitProper", "%" + unitPro + "%");
			}
			hql += " and role.id=:roleId";
			map.put("roleId", roleId);
		}
		if (StringUtils.isNotBlank(unitNo)) {
			hql += " and exists(select un.id from Unit un where us.userUnit.id=un.id and un.superCompanyCode= :unitNo)";
			map.put("unitNo", unitNo);
		}
		if (StringUtils.isNotBlank(areaId)) {
			hql += " and area.id=:areaId";
			map.put("areaId", areaId);
		}
		hql += " and enterpriseUserUseSystem=1 order by userLoginname";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return userService.toVoResult(userService.queryUsersHql(hql, page, map));
	}

	public ResultVO<UserVO> queryUsersByParent(String loginName, String roleId, String unitName, String areaId,
			Integer pageNum) {
		List<Area> list = new ArrayList<Area>();
		list = areaService.findChildren(areaId, list);
		List<String> areaIds = new ArrayList<String>();
		areaIds.add(areaId);
		for (int i = 0; i < list.size(); i++) {
			areaIds.add(list.get(i).getId());
		}
		HashMap map = new HashMap();
		String hql = "from User where role.id<>'1'";
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}

		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}

		if (StringUtils.isNotBlank(roleId)) {
			hql += " and role.id=:roleId";
			map.put("roleId", roleId);
		}
		if (areaIds.size() > 0) {
			hql += " and area.id in(:areaId)";
			map.put("areaId", areaIds.toArray());
		}
		hql += " and enterpriseUserUseSystem=1 order by userLoginname";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return userService.toVoResult(userService.queryUsersByHql(hql, map, page));
	}

	@At("/user/export")
	@Ok("jsp:/static/admin/user/export/list")
	public ResultVO<UserVO> userExport(HttpServletRequest request, @Param("p") int pageNum,
			@Param("loginName") String loginName, @Param("roleId") String roleId, @Param("unitName") String unitName) {

		return queryExportUsers(loginName, roleId, unitName, pageNum, ResultVO.DEFAULT_PAGE_SIZE, request);
	}

	@At("/user/information")
	@Ok("jsp:/static/admin/user/information/list")
	public ResultVO<UserVO> userInformation(HttpServletRequest request, @Param("p") int pageNum,
			@Param("loginName") String loginName, @Param("roleId") String roleId, @Param("unitName") String unitName) {

		return queryExportUsers(loginName, roleId, unitName, pageNum, ResultVO.DEFAULT_PAGE_SIZE, request);
	}

	@At("/user/export")
	@Ok("jsp:/static/admin/user/export/list")
	public ResultVO<UserVO> exportUser(HttpServletRequest request, @Param("p") int pageNum,
			@Param("loginName") String loginName, @Param("roleId") String roleId, @Param("unitName") String unitName) {

		return queryExportUsers(loginName, roleId, unitName, pageNum, ResultVO.DEFAULT_PAGE_SIZE, request);
	}

	@At("/user/userInfo")
	@Ok("jsp:/static/admin/user/information/list")
	public ResultVO<UserVO> queryUsers(@Param("loginName") String loginName, @Param("roleId") String roleId,
			@Param("unitName") String unitName, @Param("p") Integer pageNum, HttpServletRequest request) {

		List<Role> roleList = roleService.queryAllRoles();
		request.setAttribute("roleList", roleList);

		String hql = "from User where role.id<>'1'";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}

		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}

		if (StringUtils.isNotBlank(roleId)) {
			hql += " and role.id= :roleId";
			map.put("roleId", roleId);
		}
		hql += " and enterpriseUserUseSystem=1 order by role.id";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return userService.toVoResult(userService.queryUsersHql(hql, page, map));
	}

	@At("/dataManage/queryExportUsers")
	@Ok("jsp:/static/ocean/dataManage/listUser")
	public void queryExportUsersToPage(HttpServletRequest request) {
		// 角色列表
		List<Role> roleList = roleService.queryAllRoles();
		request.setAttribute("roleList", roleList);
	}

	@At("/dataManage/queryExportUsersData")
	@Ok("json")
	public ResultVO<UserVO> queryExportUsers(@Param("loginName") String loginName, @Param("roleId") String roleId,
			@Param("unitName") String unitName, @Param("page") Integer pageNum, @Param("rows") int pageSize,
			HttpServletRequest request) {

		request.setAttribute("loginName", loginName);
		request.setAttribute("unitName", unitName);

		// 角色列表
		List<Role> roleList = roleService.queryAllRoles();
		request.setAttribute("roleList", roleList);

		// 查询用户
		String hql = "from User where role.id<>'1' and enterpriseUserUseSystem=1";
		// String[] paras = new String[3];
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}

		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}

		if (StringUtils.isNotBlank(roleId)) {
			hql += " and role.id= :roleId";
			map.put("roleId", roleId);
		}

		// 用户标志，1：已经导出，和外网同步 0：新填或修改，没有导出后与外网同步
		hql += " and userFlag='0'";
		hql += " order by userLoginname";

		Page page = null;
		if (pageNum != null && pageNum != 0) {
			page = new Page(pageNum, pageSize);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return userService.toVoResult(userService.queryUsersHql(hql, page, map));
	}

	@At("/user/editUser")
	@Ok("jsp:/static/admin/user/information/editUser")
	public void userInfoEdit(String id, HttpServletRequest request) {
		UserVO user = queryUserById(id);
		request.setAttribute("user", user);

		List<String> userIndustry = user.getUserIndustrys();
		request.setAttribute("userIndustry", userIndustry);

		String unitId = user.getUserUnitId();
		UnitVO unit = unitWS.queryUnitById(unitId, request);
		request.setAttribute("unit", unit);

		List<AuthorityVO> authorList = new ArrayList<AuthorityVO>();
		authorList = this.queryAuthority(null, null).getOperationResult();
		request.setAttribute("authorList", authorList);

		List<IndustryVO> industryList = industryWS.queryIndustryList().getOperationResult();

		for (IndustryVO funcVoAll : industryList) {
			for (String funcVoselect : userIndustry) {
				if (funcVoAll.getId().equals(funcVoselect)) {
					funcVoAll.setCheck(true);
					break;
				}
			}
		}
		request.setAttribute("industryList", industryList);
	}

	public List<UserVO> queryAllEnterpriseUsers() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("role.id");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.ORVALUE, "role.id", "3", "5"));
		return userService.toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	// 按照地区查找企业用户,自加

	public List<UserVO> queryAreaEnterpriseUsers(String userAreaId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("role.id");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.ORVALUE, "role.id", "3", "5"));
		if (userAreaId == null) {
			filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "area.id", null));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}
		return userService.toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	// 按照地区查找省区海洋局用户，自加

	public List<UserVO> queryAreaOceanUsers(String userAreaId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("userUnit");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", "4"));// 现省局级角色id为4
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));

		return userService.toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	// 查找所有省区用户

	public List<UserVO> queryAllAreaOcean() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("userUnit");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", "4"));
		filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "area.id", null));

		return userService.toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	public List<UserVO> queryAllUsersByIndustryId(String industryId) {
		if (StringUtils.isNotBlank(industryId)) {
			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "industry.id", industryId));
			List<UserIndustry> userIndustry = userService.getUserIndustry(filter);
			if (userIndustry != null && userIndustry.size() > 0) {
				String hql = "from User as u where (u.role.id=3 or u.role.id=5) and exists (select ui.id from UserIndustry ui where ui.user.id=u.id and ui.industry.id=:industryId) order by u.userLoginname";
				HashMap map = new HashMap();
				map.put("industryId", industryId);
				// Filter filter2 = new Filter();
				// String uids = "";
				// for (UserIndustry ui : userIndustry) {
				// String id = ui.getUser().getId();
				// uids += id + ",";
				// }
				// String[] split = uids.split(",");
				// filter2.setOrder(FilterConstant.ASC);
				// filter2.setSortBy("userLoginname");
				// filter2.addRule(new FilterRule(FilterConstant.COLLECTION,
				// "id", split));
				// filter2.addRule(new FilterRule(FilterConstant.ORVALUE,
				// "role.id", "3", "5"));
				return userService.toVoResult(userService.queryUsersByHql(hql, map, null)).getOperationResult();
			}
		}
		return new ArrayList<UserVO>();
	}

	public List<UserVO> queryUsersByIndustryId(String industryId, String areaId) {
		List<UserVO> users = new ArrayList<UserVO>();
		UserVO user = new UserVO();
		if (StringUtils.isNotBlank(industryId)) {
			Industry industry = industryService.queryIndustryById(industryId);
			for (UserIndustry userIndustry : industry.getUserIndustrys()) {
				user = this.queryUserById(userIndustry.getUser().getId());
				// 取本行政区划的行业用户
				if (areaId.equals(user.getUserAreaId())) {
					users.add(user);
				}
			}
		}
		return users;
	}

	public void removeUsers(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			userService.removeUsers(arrIds);
		}
	}

	public void changePassword(String loginName, String oldPwd, String newPwd) {
		userService.changePassword(loginName, oldPwd, newPwd);
	}

	@At("/user/resetPassword")
	@Ok("json")
	public Map<String, String> resetPassword(@Param("id") String id, HttpServletRequest request) {
		cn.com.generaldata.os.pojo.User user = userService.queryUserById(id);
		user.setUserPasswd(MD5Util.getMD5ofStr(DEFAULT_PASSWORD));
		userService.modifyUser(user);
		return CommonUtil.createOKMsg("重置成功。");
	}

	public UserVO modifyUserIndustryIds(UserVO user) {
		return userService.toVo(userService.modifyIndustry(toPojo(user), toPojoIndustrys(user)));
	}

	public UserVO addEnterpriseIndustryIds(UserVO user) {
		return userService.toVo(userService.addEnterpriseIndustry(toPojo(user), toPojoEnterpriseIndustrys(user)));
	}

	public UserVO deleteUserIndustryIds(UserVO user, String industryId) {
		return userService.toVo(userService.deleteIndustry(toPojo(user), industryId));
	}

	public UserVO deleteEnterpriseIndustryIds(UserVO user, String industryId) {
		return userService.toVo(userService.deleteEnterpriseIndustry(toPojo(user), industryId));
	}

	private cn.com.generaldata.os.pojo.User toPojo(UserVO user) {
		if (user != null) {
			cn.com.generaldata.os.pojo.User userPO = userService.queryUserById(user.getId());

			Role pRole = new Role();
			Area pArea = new Area();
			pRole.setId(user.getRoleId());
			pArea.setId(user.getUserAreaId());

			// Industry pIndustry = null;
			// if (StringUtils.isNotBlank(user.getIndustryId())) {
			// pIndustry = new Industry();
			// pIndustry.setId(user.getIndustryId());
			// }
			Unit unit = null;
			if (StringUtils.isNotBlank(user.getUserUnitId())) {
				unit = new Unit();
				unit.setId(user.getUserUnitId());
				unit.setUnitName(user.getUserUnit());
			}
			if (userPO != null) {
				userPO.setArea(pArea);
				userPO.setRole(pRole);
				userPO.setUserLoginname(user.getUserLoginname());
				userPO.setUserUnit(unit);
				userPO.setAuthorId(user.getAuthorId());
				userPO.setEnterpriseUserUseSystem(user.getEnterpriseUserUseSystem());
				return userPO;
			} else {
				return new cn.com.generaldata.os.pojo.User(user.getId(), pRole, user.getIndustryId(), pArea,
						user.getUserLoginname(), user.getUserPasswd(), user.getUserRegionName(),
						user.getUserRegionOcean(), user.getUserCityName(), user.getUserDepartmentName(),
						user.getUserRegionCode(), unit, user.getUserInstitutionName(), user.getUserInstitutionCode(),
						user.getUserDomainName(), user.getUserDomainCode(), user.getUserUnitAdmin(),
						user.getUserStatAdmin(), user.getUserFillAdmin(), user.getUserContactPerson(),
						user.getUserContactPhone(), user.getUserFlag(), user.getDl(), user.getZl(), user.getXl(),
						user.getLm(), user.getHyl(), user.getAddr(), user.getQh(), user.getYwhd(), user.getMc(),
						user.getDwfl(), user.getHy2002(), user.getHy2001(), user.getZclx(), user.getKgqk(),
						user.getJglx(), user.getYyzt(), user.getLsgx(), user.getBbdw(), user.getUserStatAdminTel(),
						user.getUserStat(), user.getUserStatTel(), user.getUserFaxTel(), user.getUserEmial(),
						user.getCompanyUrl(), user.getProduct1(), user.getProduct2(), user.getProduct3(),
						user.getOceanIndustryName(), user.getOceanIndustryCode(), user.getMostlyTaking(),
						user.getSuperCompany(), user.getSuperCompanyCode(), user.getRegistAdd(),
						user.getCompanySynopsis(), user.getUserReportedDataType(), user.getCorporationAndTel(),
						user.getPractitioner(), user.getAssetTotal(), user.getTaking(),
						user.getEnterpriseUserUseSystem(), null, null, null, null, user.getAuthorId());
			}
		}
		return null;
	}

	private List<Industry> toPojoIndustrys(UserVO user) {
		if (user != null) {
			List<Industry> industrys = new ArrayList<Industry>();
			if (user != null) {
				for (String industry : user.getUserIndustrys()) {
					Industry industryId = new Industry();
					industryId.setId(industry);
					industrys.add(industryId);
				}
			}
			return industrys;
		}
		return new ArrayList<Industry>();
	}

	private List<Industry> toPojoEnterpriseIndustrys(UserVO user) {
		if (user != null) {
			List<Industry> industrys = new ArrayList<Industry>();
			if (user != null) {
				for (String industry : user.getEnterpriseIndustrys()) {
					Industry industryId = new Industry();
					industryId.setId(industry);
					industrys.add(industryId);
				}
			}
			return industrys;
		}
		return new ArrayList<Industry>();
	}

	/**
	 * 模拟登录.
	 * 
	 * @param user
	 *            用户数据
	 * @param request
	 * @param session
	 * @return
	 */
	@At("/user/login")
	@POST
	@Fail("jsp:/static/user/login")
	@Filters
	public View login(@Param("..") cn.com.generaldata.os.vo.UserVO user, HttpServletRequest request, HttpSession session) {

		// 取出用户
		User user1 = userService.loginNew(user.getUserLoginname());
		UserVO voUser = userService.toVo(userService.loginNew(user.getUserLoginname()));
		if (user1 == null) {
			request.setAttribute("msg", "用户不存在。");
			throw new RuntimeException("用户不存在。");
		}

		if (!MD5Util.getMD5ofStr(user.getUserPasswd()).equals(user1.getUserPasswd())) {
			request.setAttribute("msg", "密码错误。");
			throw new RuntimeException("密码错误。");
		}

		// 保存到session
		session.setAttribute("user", voUser);

		// 单点登录，提供了username和accessMap，放在了session中
		// 这里得模拟一下。
		session.setAttribute("username", user.getUserLoginname());
		
		//获取用户权限
		session.setAttribute("moduleNameStr", userService.getModuleName(user1.getAuthorId()));

		// 根据角色ID处理
		String roleId = voUser.getRoleId();
		if (roleId.equals("1")) {
			// 系统管理员
			return new JspView("/static/admin/main");
		} else if (roleId.equals("3") || roleId.equals("5")) {
			// 企业用户，涉海部分禁止内网
			return new JspView("/static/company/main");
		} else if (roleId.equals("4")) {
			// 省区局用户，或者叫海洋局用户
			return new ServerRedirectView("/mainTitle/main");
		}

		return new JspView("/static/forbidden");

	}
	
	/**
	 * 首页.
	 * 
	 */
	@At("/")
	@Ok("jsp:/static/user/login")
	public void showIndex(HttpServletRequest request) {
		System.out.println("111");
		// 实际应用时，直接根据用户名，取用户，跳转到不同的菜单页面。
		// 现在是模拟，所以跳到登录页面
	}

	/**
	 * 退出登录.
	 * @param session
	 */
	@At("/user/logout")
	@Ok("jsp:/static/user/login")
	@Filters
	public void logout(HttpSession session) {
		session.invalidate();
	}

}
